package com.example.demo.common;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.entity.BuildingInfo;
import com.example.demo.entity.RoomInfo;
import com.example.demo.mapper.BuildingInfoMapper;
import com.example.demo.mapper.RoomInfoMapper;
import com.example.demo.utils.RedisUtil;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author chen huilong
 * @data 2022/10/26
 */
@Component // 主要用于标记配置类，兼备Component的效果
@EnableScheduling // 开启定时任务
public class ScheduledTask {

    private static String ROOM = "ROOM";

    @Resource
    private BuildingInfoMapper buildingInfoMapper;

    @Resource
    private RoomInfoMapper roomInfoMapper;

    @Resource
    private RedisUtil redisUtil;

    // 定时任务，每天上午11:45触发
    @Scheduled(cron = "0 45 11 ? * * ")
    private void asyncDBtoRedis() {
        System.err.println("执行定时任务时间: " + new Date());

        // 保存每栋楼的信息到Redis
        List<BuildingInfo> buildingInfos = buildingInfoMapper.selectList(null);
        for (BuildingInfo buildingInfo : buildingInfos) {
            redisUtil.set(buildingInfo.getBuildingId() + "", buildingInfo);

            // 保存每栋楼的宿舍信息列表到Redis
            QueryWrapper<RoomInfo> roomInfoQueryWrapper = new QueryWrapper<>();
            roomInfoQueryWrapper.eq("building_id", buildingInfo.getBuildingId());
            // 剩余床位大于等于1
            roomInfoQueryWrapper.ge("bed_remainder", 1);
            List<RoomInfo> roomInfos = roomInfoMapper.selectList(roomInfoQueryWrapper);
            redisUtil.set(ROOM + buildingInfo.getBuildingId(), roomInfos);
        }
    }


    // 定时任务，每天上午12:15触发
    @Scheduled(cron = "0 15 12 ? * * ")
    private void asyncRedistoDB() {
        System.err.println("执行定时任务时间: " + new Date());

        // 保存每栋楼的信息到Redis
        List<BuildingInfo> buildingInfos = buildingInfoMapper.selectList(null);
        for (BuildingInfo buildingInfo : buildingInfos) {
            BuildingInfo b = (BuildingInfo) redisUtil.get(buildingInfo.getBuildingId() + "");
            buildingInfoMapper.updateById(b);
            List<RoomInfo> bs = (List<RoomInfo>) redisUtil.get(ROOM + buildingInfo.getBuildingId());
            for(RoomInfo roomInfo : bs) {
                roomInfoMapper.updateById(roomInfo);
            }
        }
    }


}
